# Create your views here.
from datetime import datetime, timedelta
import urllib

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.utils import simplejson as json
from django.template.loader import get_template
from django.template import Context

from mhd.locator import MHD_StopLocator
from mhd.parser import MHD_RouteParser
from mhd.planner import JourneyPlanner

from web.service.HttpReader import HttpReader
from web.service.GeoCodingBroker import GeoCodingBroker
from infra.util.geoutil import LatLng

jp = JourneyPlanner()


def index(request):    
    return render_to_response('mhd/index.html')

# TODO: make date, time parametric


def find_route(request):
    try:
        geoCodingBroker = GeoCodingBroker()
        (lat1, lng1, acuracy1) = geoCodingBroker.geoCode(street = request.GET['a'], streetNum = '', city = u'Bratislava')
        (lat2, lng2, acuracy2) = geoCodingBroker.geoCode(street = request.GET['b'], streetNum = '', city = u'Bratislava')
        
        for connection in jp.getPlan(LatLng(lat1, lng1), LatLng(lat2, lng2)):
            print connection
        
        
        return HttpResponse("TODO")
    except Exception, e:
        print e
        return HttpResponse(e)

    
                
def find_route__(request):
    try:
        mhd_stop_locator = MHD_StopLocator()
        loc_a = mhd_stop_locator.find_nearest_stop(street = request.GET['a'], streetNum = '', city = u'Bratislava')
        loc_b = mhd_stop_locator.find_nearest_stop(street = request.GET['b'], streetNum = '', city = u'Bratislava')
        
#        url = 'http://www.imhd.zoznam.sk/ba/index.php?w=3825242e29ef21292e252a2f3033ef2f302523ea&lang=&z1x=%s&z2x=%s&odpr=0&datum=%s&cas=%s&mnp=2&np=5&ptyp=0&rch=1' \
#            % (urllib.quote_plus(loc_a['stop'].name.encode('cp1250')), urllib.quote_plus(loc_b['stop'].name.encode('cp1250')), 
#               urllib.quote_plus(datetime.now().strftime("%d.%m.%Y")), 
#               urllib.quote_plus((datetime.now() + timedelta(minutes = 10)).strftime("%H:%M")))

        url = 'http://www.imhd.zoznam.sk/ba/index.php?w=3825242e29ef21292e252a2f3033ef2f302523ea&lang=&z1x=%s&z2x=%s&odpr=0&datum=%s&cas=%s&mnp=2&np=5&ptyp=0&rch=1' \
			% (urllib.quote_plus(loc_a['stop'].name.encode('cp1250')), urllib.quote_plus(loc_b['stop'].name.encode('cp1250')), 
			   urllib.quote_plus("13.07.2011"), 
			   urllib.quote_plus("17:00"))

    
        httpReader = HttpReader()
        data = httpReader.read(url = url)
                
        mhd_routeParser = MHD_RouteParser()
        route_connections = mhd_routeParser.parse(data.decode('cp1250'))
        
        warning_dir = get_template('mhd/warning_dir.html');
        start_addr_dir = get_template('mhd/address_block.html');                
        end_addr_dir = get_template('mhd/address_block.html');
        dir_summary_block = get_template('mhd/dir_summary_block.html');
        dir_step_block = get_template('mhd/dir_step_block.html');
        
        status = 'success'        
        if len(route_connections) == 0:
            status = 'no route to destination'
        
        response = {'loc_a': {'lat':loc_a['lat'], 'lng':loc_a['lng']}, 
                    'loc_b': {'lat':loc_b['lat'], 'lng':loc_b['lng']},
                    'route_conns': route_connections,
                    'warning_dir': warning_dir.render(Context()),
                    'start_addr_dir': start_addr_dir.render(Context()),
                    'end_addr_dir': end_addr_dir.render(Context()),
                    'dir_summary_block': dir_summary_block.render(Context()),
                    'dir_step_block': dir_step_block.render(Context()),
                    'status': status}
    
        return HttpResponse(json.dumps(response))
    except Exception, e:
        print e
        return HttpResponse(e)
        
